package com.kfm.common.domain.serial;


import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

/**
 * 自定义 GrantedAuthority 反序列化器
 */
public class GrantedAuthorityDeserializer extends StdDeserializer<Set<SimpleGrantedAuthority>> {

    public GrantedAuthorityDeserializer() {
        this(SimpleGrantedAuthority.class);
    }

    public GrantedAuthorityDeserializer(Class<?> vc) {
        super(vc);
    }
    @Override
    public Set<SimpleGrantedAuthority> deserialize(JsonParser jp, DeserializationContext ctx) throws IOException, JacksonException {
        JsonNode node = jp.getCodec().readTree(jp);
        Set<SimpleGrantedAuthority> authorities = new HashSet<>();
        if (node.isArray()) {
            for (JsonNode element : node) {
                String authority = element.get("authority").asText();
                authorities.add(new SimpleGrantedAuthority(authority));
            }
        }
        return authorities;
    }
}
